package dao

import (
	"context"
	"mini-app/internal/dal"
	"mini-app/internal/models"
	"time"

	"gorm.io/gorm"
)

type Goods struct{}

// LastestOrder 最近购买记录
func (Goods) LastestOrder(
	ctx context.Context,
	db *gorm.DB,
	goodsID string,
	page, limit int,
) (records []models.Order, total int64) {
	tx := db.WithContext(ctx).Model(&models.Order{}).
		Where("goods_id = ?", goodsID).                      // 商品
		Where("created_at > ?", time.Now().Unix()-3600*24*7) // 最近7天
	tx.Count(&total)
	if limit > 0 {
		if limit > 2000 {
			limit = 2000
		}
		tx = tx.Limit(limit)
	}
	if page > 0 && limit > 0 {
		tx = tx.Offset((page - 1) * limit)
	}
	tx.Order("created_at desc").
		Select("openid", "goods_id", "created_at").
		Find(&records)
	return
}

// List 分类列表
func (Goods) ClassList(
	ctx context.Context,
	query *dal.Query,
	robotID string,
) ([]*models.GoodsSetting, error) {
	c := query.GoodsSetting
	return c.WithContext(ctx).
		Where(c.RobotID.Eq(robotID)).
		Where(c.GoodsClass.IsNotNull()).
		Where(c.GoodsClass.Neq("")).
		Where(c.Visible.Eq(1)).
		Group(c.GoodsClass).
		Order(c.GoodsClass).
		Find()
}
